package cn.teduymdj.passport.filter;

import cn.teduymdj.passport.security.LoginPrincipal;
import cn.teduymdj.passport.web.JsonResult;
import cn.teduymdj.passport.web.ServiceCode;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>JWT过滤器</p>
 *
 * <p>此JWT的主要作用：</p>
 * <ul>
 *     <li>获取客户端携带的JWT，惯用做法是：客户端应该通过请求头中的Authorization属性来携带JWT</li>
 *     <li>解析客户端携带的JWT，并创建出Authentication对象，存入到SecurityContext中</li>
 * </ul>
 *
 * @author java@tedu.cn
 * @version 0.0.1
 */
@Slf4j
@Component
public class JwtAuthorizationFilter extends OncePerRequestFilter {
    /**
     * jwt字符串最小长度
     */
    public static final int JWT_MIN_LENGTH = 113;

    @Value("${ymdj.jwt.secret-key}")
    private String secretKey;

    public JwtAuthorizationFilter() {
        log.info("创建过滤器对象,JwtAuthorizationFilter");
    }

    @Override
    protected void doFilterInternal
            (HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        log.debug("JwtAuthorizationFilter开始执行过滤……");
        //清空security上下文
        //security上下文中的认证信息会被清除
        // 避免前序携带JWT且解析成功后将认证信息存入Security上下文后，后续不携带JWT也能访问的“问题”
        SecurityContextHolder.clearContext();
        //获取客户端携带的jwt
        String jwt = request.getHeader("Authorization");
        log.debug("接收到的jwt,{}",jwt);

        //检查是否获取到了基本有效的jwt
        if (!StringUtils.hasText(jwt)||jwt.length()<JWT_MIN_LENGTH){
           //对于无效的jwt,直接放行,交由后续组件处理
            log.debug("当前jwt视为无效,将放行");
            filterChain.doFilter(request, response);
            return;
        }
        //尝试解析jwt
        log.debug("获取到的JWT被视为有效，准备解析JWT……");
        response.setContentType("application/json; charset=utf-8");
        String message = "非法访问";
        Claims body = null;
        try {
            body = Jwts.parser()
                    .setSigningKey(secretKey)
                    .parseClaimsJws(jwt)
                    .getBody();
        } catch (ExpiredJwtException e) {
            log.debug("解析jwt时出现了ExpiredJwtException");
            ServiceCode serviceCode = ServiceCode.ERR_JWT_EXPIRED;
            message = "登录信息已过期，请重新登录！";
            JsonResult<Void> jsonResult = JsonResult.fail(serviceCode, message);
            String jsonResultString = JSON.toJSONString(jsonResult);
            response.setContentType("application/json; charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.println(jsonResultString);
            return;
        }  catch (MalformedJwtException e) {
            log.debug("解析jwt时出现了MalformedJwtException");
            ServiceCode serviceCode = ServiceCode.ERR_JWT_MALFORMED;
            JsonResult<Void> jsonResult = JsonResult.fail(serviceCode, message);
            String jsonResultString = JSON.toJSONString(jsonResult);
            response.setContentType("application/json; charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.println(jsonResultString);
            return;
        } catch (SignatureException e) {
            log.debug("解析jwt时出现了SignatureException");
            ServiceCode serviceCode = ServiceCode.ERR_JWT_SIGNATURE;
            JsonResult<Void> jsonResult = JsonResult.fail(serviceCode, message);
            String jsonResultString = JSON.toJSONString(jsonResult);
            response.setContentType("application/json; charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.println(jsonResultString);
            return;
        } catch (Throwable e) {
            log.debug("解析JWT时出现Throwable，需要开发人员在JWT过滤器补充对异常的处理");
            e.printStackTrace();
            message = "你有异常没有处理，请根据服务器端控制台的信息，补充对此类异常的处理！！！";
            PrintWriter writer = response.getWriter();
            writer.println(message);
            return;
        }
        String username = body.get("username", String.class);
        Long id = body.get("id", Long.class);
        String authoritiesToString = body.get("authoritiesToString", String.class);
        LoginPrincipal loginPrincipal = new LoginPrincipal(id, username);
        log.debug("解析jwt结果{}",loginPrincipal);
        List<SimpleGrantedAuthority> authorities =
                JSON.parseArray(authoritiesToString, SimpleGrantedAuthority.class);


        //创建authentication对象
        UsernamePasswordAuthenticationToken authentication =
                new UsernamePasswordAuthenticationToken(
                        loginPrincipal, null, authorities);

        //将authentication对象存入SecurityContext中
        log.debug("向SecurityContext中存入认证信息{},权限信息{}",loginPrincipal,authorities);
        SecurityContextHolder.getContext().setAuthentication(authentication);

        // 过滤器链继续向后传递，即：放行
        log.debug("过滤器链继续向后传递，即：放行");
        filterChain.doFilter(request, response);
    }
}
